<?php

/**
 * @author Bart Hanssens <bart.hanssens@fedict.be>
 */

$https = empty($_SERVER['HTTPS']) ? 'N' : 'Y';
$ip = $_SERVER['REMOTE_ADDR'];
$forward = get_forward_ip();
$port = $_SERVER['REMOTE_PORT'];
$agent = $_SERVER['HTTP_USER_AGENT'];  

$cookie = get_cookie($ip, $port);
setcookie('eyeballs', $cookie, 0);
store_session($cookie, $https, $ip, $forward, $agent);


/**
 * Create cookie ID based upon current (micro)time
 */
function create_cookie($ip, $port) {
	$str = $ip . $port . round(microtime(true) * 1000);
	return hash('md2', $str);
}

/**
 * Get the current cookie from the session or create a new cookie
 *
 * @return string
 *  Cookie ID
 */
function get_cookie($ip, $port) {
	return empty($_COOKIE['eyeballs']) ? create_cookie($ip, $port) : $_COOKIE['eyeballs'];
}

/**
 * Get the client IP address in case the request is proxied
 *
 * @return mixed
 *  IP address or null
 */
function get_forward_ip() {
	$forward = null;

	if (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		return $_SERVER['HTTP_X_FORWARDED_FOR'];
	} 
	if (! empty($_SERVER['HTTP_CLIENT_IP'])) {
		return $_SERVER['HTTP_CLIENT_IP'];
	} 
	return $forward;

}

/**
 * Get cookie parameter
 *
 * @return string
 *  Cookie GET parameter
 */
function get_cookie_param() {
	return htmlspecialchars($_GET['cookie']);
}

?>
